/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package model.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author K u Ku
 */
public class ConnectionFactory {
    static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    static String url = "jdbc:sqlserver://localhost:1433;databaseName=TrainingCenter;user=sa;password=123456";
    private static Connection conn;
    
    public static Connection getConnection(){
        try {
            Class.forName(driver);
            if(conn==null){
                conn = DriverManager.getConnection(url);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
        return conn;
    }  
    
    //Load data to table
    public static void getDataToTable(String strSql, JTable tableName) throws SQLException{
        DefaultTableModel dm = (DefaultTableModel) tableName.getModel();
        for (int i = dm.getRowCount() - 1; i >= 0; i--) {
            dm.removeRow(i);
        }
        Vector cols = new Vector();
        try {
            ResultSet rs = util.Helper.queryResultSet(strSql);
            ResultSetMetaData rm = rs.getMetaData();
            for (int i = 1; i <= rm.getColumnCount(); i++) {
                cols.add(rm.getColumnName(i));
            }
            dm.setColumnIdentifiers(cols);
            while (rs.next()) {
                Vector row = new Vector();
                for (int i = 1; i <= rm.getColumnCount(); i++) {
                    row.add(rs.getString(i));
                }
                dm.addRow(row);
            }
            tableName.setModel(dm);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}
